package test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author tongchen
 * @create 2023-02-20 11:17
 */
public class TcpEchoClient {
    //创建socket
    private Socket socket;
    //构造方法创建socket

    public TcpEchoClient(String address,int port) throws IOException {
        this.socket=new Socket(address, port);
    }
    //连接
    public void start(){
        System.out.printf("客户端启动成功....");
        try(InputStream inputStream=socket.getInputStream(); OutputStream outputStream=socket.getOutputStream()){
            //循环输入
            while(true){
                System.out.println("->");
                Scanner scan=new Scanner (System.in);
                String request=scan.nextLine();
                //验证request的有效性
                if(request==null||request.equals("")){
                    System.out.println("输入的请求不能为空");
                    continue;
                }
                //将request输入到socket
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);
                //强制刷新
                printWriter.flush();
                //在socket中获取请求
                Scanner scanner = new Scanner(inputStream);
                String response = scanner.nextLine();
                System.out.printf("request = %s, response = %s\n", request, response);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }
        //循环输入

    }
    //验证‘=
    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1", 9090);
        tcpEchoClient.start();
    }
}
